package hui.zhang.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import hui.zhang.domain.base.Area;
import hui.zhang.service.base.AreaService;
import hui.zhang.utils.PinYin4jUtils;

@Controller
@ParentPackage("struts-default")
@Namespace("/")
@Scope("prototype")
public class AreaAction extends ActionSupport implements ModelDriven<Area>{

	//模型驱动
	private Area area = new Area();
	public Area getModel() {
		return area;
	}
	
	//注入service
	@Autowired
	private AreaService areaService;
	
	//文件上传
	private File file;
	public void setFile(File file) {
		this.file = file;
	}


	/**
	 * 批量导入 解析excel
	 * @return
	 * @throws Exception
	 */
	@Action(value="area_batchImport")
	public String batchImport() throws Exception {
		//解析xls文件 用hssf
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
		List<Area> list = new ArrayList<Area>();
		for (Row row : sheet) {
			//如果是第一行表头 跳过
			if (row.getRowNum() == 0) {
				continue;
			}
			//跳过空行
			if(row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			
			//生成省市区编码和简码
			String province = area.getProvince();
			//去掉 省 字
			province = province.substring(0, province.length()-1);
			String city = area.getCity();
			city = city.substring(0, city.length()-1);
			String district = area.getDistrict();
			district = district.substring(0, district.length()-1);
			//简码
			String[] headByString = PinYin4jUtils.getHeadByString(province+city+district);
			StringBuilder sb = new StringBuilder();
			for (String string : headByString) {
				sb.append(string);
			}
			String shortcode = sb.toString();
			area.setShortcode(shortcode);
			//城市编码
			String citycode = PinYin4jUtils.hanziToPinyin(city,"");
			area.setCitycode(citycode);
			list.add(area);
		}
		areaService.save(list);
		return NONE;
	}
	
	//分页属性封
	private Integer page;
	private Integer rows;
	public void setPage(Integer page) {
		this.page = page;
	}
	public void setRows(Integer rows) {
		this.rows = rows;
	}


	/**
	 * 分页 条件查询
	 * @return
	 */
	@Action(value="area_pageQuery")
	public String findAllByPage() {
		Pageable pageable = new PageRequest(page-1, rows);
		Specification<Area> specification = new Specification<Area>() {
			List<Predicate> list = new ArrayList<Predicate>();
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				if (StringUtils.isNotBlank(area.getProvince())) {
					Predicate p1 = cb.like(root.get("province").as(String.class), "%"+area.getProvince()+"%");
					list.add(p1);
				}
				if(StringUtils.isNotBlank(area.getCity())) {
					Predicate p2 = cb.like(root.get("city").as(String.class), "%"+area.getCity()+"%");
					list.add(p2);
				}
				if(StringUtils.isNotBlank(area.getDistrict())) {
					Predicate p3 = cb.like(root.get("district").as(String.class), "%"+area.getDistrict()+"%");
					list.add(p3);
				}	
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		Page<Area> pageData = areaService.findAll(specification, pageable);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", pageData.getTotalElements());
		map.put("rows", pageData.getContent());
		String jsonString = JSONObject.toJSONString(map);
		try {
			ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return NONE;
	}
	
	@Action(value="area_findAll")
	public String findAll() {
		List<Area> list = areaService.findAll();
		String jsonString = JSONObject.toJSONString(list);
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		try {
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return NONE;
	}
	
	@Action(value="queryProvince")
	public String queryProvince() {
		List<String> provinces = areaService.queryProvince();
		List<Map<String,String>> array = new ArrayList<Map<String,String>>();
		for (String p : provinces) {
			Map<String, String> map = new HashMap<String,String>();
			map.put("province", p);
			array.add(map);
		}
		String jsonString = JSONObject.toJSONString(array);
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		try {
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return NONE;
	}
	@Action(value="queryCity")
	public String queryCity() {
		String province = area.getProvince();
		List<String> cities = areaService.queryCity(province);
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		for (String c : cities) {
			Map<String,String> map = new HashMap<String,String>();
			map.put("city", c);
			list.add(map);
		}
		String jsonString = JSONObject.toJSONString(list);
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		try {
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return NONE;
	}
	@Action(value="queryDistrict")
	public String queryDistrict() {
		String city = area.getCity();
		List<Area> list = areaService.queryDistrict(city);
		String jsonString = JSONObject.toJSONString(list);
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		try {
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return NONE;
	}

}
